package com.softtown.modules.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softtown.common.enums.MessageSendWayEnum;
import com.softtown.common.enums.MsgSendWayTypeEnum;
import com.softtown.common.enums.MsgTypeEnum;
import com.softtown.common.exception.ErrorCode;
import com.softtown.common.exception.RenException;
import com.softtown.common.service.impl.BaseServiceImpl;
import com.softtown.common.utils.DateUtils;
import com.softtown.modules.message.service.SysEmailService;
import com.softtown.modules.message.sms.AbstractSmsService;
import com.softtown.modules.message.sms.SmsFactory;
import com.softtown.modules.oss.cloud.OSSFactory;
import com.softtown.modules.security.user.SecurityUser;
import com.softtown.modules.sys.dao.CompSysUserApplDao;
import com.softtown.modules.sys.dto.CompSysUserApplPageDTO;
import com.softtown.modules.sys.dto.JoinCompanyDTO;
import com.softtown.modules.sys.entity.*;
import com.softtown.modules.sys.enums.AprvResultEnum;
import com.softtown.modules.sys.enums.AprvStatusEnum;
import com.softtown.modules.sys.service.*;
import com.softtown.modules.sys.vo.UserEmplPermitVO;
import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: Dingyayong
 * @Date: 2019/6/3 17:11
 * @Description:
 */
@Service
public class CompSysUserApplServiceImpl extends BaseServiceImpl<CompSysUserApplDao, CompSysUserApplEntity> implements CompSysUserApplService {

    @Resource
    private SysEmailService sysEmailService;

    @Resource
    private SysParamsService sysParamsService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMsgSendWayService sysMsgSendWayService;

    @Resource
    private SysCompService sysCompService;

    @Resource
    private SysMessageService sysMessageService;

    private static final String EAMIL = "MAIL_SERVICE_IS_USABLE";
    private static final String SMS = "SMS_SERVICE_IS_USABLE";
    private static final String YES = "Y";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void joinCompany(SysCompEntity sysCompEntity, JoinCompanyDTO joinCompanyDTO) {
        CompSysUserApplEntity compSysUserApplEntity = new CompSysUserApplEntity();
        compSysUserApplEntity.setApplDate(new Date());
        compSysUserApplEntity.setAprvStatus(AprvStatusEnum.INAPPROVAL.value());
        compSysUserApplEntity.setUserId(joinCompanyDTO.getUserId());
        compSysUserApplEntity.setCompId(sysCompEntity.getId());
        compSysUserApplEntity.setMemo(joinCompanyDTO.getMemo());
        insert(compSysUserApplEntity);
        SysUserEntity sysUserEntity
                 = sysUserService.getByUserId(joinCompanyDTO.getUserId());
        SysUserEntity sysUserEntityComp
                = sysUserService.getByUserId(sysCompEntity.getAdminUserId());
        if(sysUserEntityComp.getEmail() !=null){
            String email =sysParamsService.getValue(EAMIL);
            if(email.equals(YES)){
                sysEmailService.sendEmailByUserEmpl(sysUserEntityComp.getEmail(),sysCompEntity.getName(),sysUserEntity.getUsername());
            }
        }
        if (sysUserEntityComp.getMobile() !=null){
            String sms =sysParamsService.getValue(SMS);
            if(sms.equals(YES)){
                SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                        SMS.value(), MsgTypeEnum.EMPL_JOIN_APPL.value());
                //TODO 多语言
                String smsCode =sysUserEntity.getUsername() +"|"+ "申请加入贵公司";
                //短信服务
                AbstractSmsService service = SmsFactory.build();
                if(service == null){
                    throw new RenException(ErrorCode.SMS_CONFIG);
                }
               service.sendSmsByLogin(sysUserEntityComp.getMobile(),sysMsgSendWayEntity.getMsgTemplateCode(),smsCode);
            }
        }
        // 获取消息发送方式
        SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                STTATION_LETTER.value(), MsgTypeEnum.EMPL_JOIN_APPL.value());
        Object[] titleArray = new Object[]{sysCompEntity.getName()};
        String title = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateTitle(), titleArray);
        Object[] contentArray = new Object[]{sysUserEntity.getUsername()};
        String content = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateContent(), contentArray);
        // 发送消息
        Date nowDate = new Date();
        SysMessageEntity sysMessageEntity = new SysMessageEntity();
        sysMessageEntity.setMsgSendWayType(MessageSendWayEnum.APP.value());
        sysMessageEntity.setMsgCompId(sysCompEntity.getId());
        sysMessageEntity.setType(MsgTypeEnum.EMPL_JOIN_APPL.value());
        sysMessageEntity.setCreateDate(nowDate);
        sysMessageEntity.setCreator(SecurityUser.getUser().getId());
        sysMessageEntity.setReceiverId(sysCompEntity.getAdminUserId());
        // 0是未读，1是已读
        sysMessageEntity.setIsRead(0);
        sysMessageEntity.setSendDate(nowDate);
        sysMessageEntity.setSenderId(joinCompanyDTO.getUserId());
        sysMessageEntity.setContent(content);
        sysMessageEntity.setTitle(title);
        sysMessageEntity.setUpdateDate(nowDate);
        sysMessageEntity.setUpdater(SecurityUser.getUser().getId());
        sysMessageEntity.setUpdateTimestamp(Long.toString(System.currentTimeMillis()));
        sysMessageService.insert(sysMessageEntity);
    }

    @Override
    public UserEmplPermitVO permitList(Long compId) {
        return baseDao.permitList(compId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refuse(Long compId, Long userId, Long compUserId) {
        CompSysUserApplEntity compSysUserApplEntity = baseDao.findByCompIdAndUserId(compId, userId);
        compSysUserApplEntity.setAprvUserId(compUserId);
        compSysUserApplEntity.setAprvStatus(AprvStatusEnum.COMPLETEAPPROVAL.value());
        compSysUserApplEntity.setAprvEndResult(AprvResultEnum.APPROVALREFUSE.value());
        compSysUserApplEntity.setAprvEndDate(new Date());
        compSysUserApplEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
        compSysUserApplEntity.setIsDeleted(null);
        baseDao.updateComUserAppl(compSysUserApplEntity);
        SysUserEntity sysUserEntity
                = sysUserService.getByUserId(userId);
        SysCompEntity sysCompEntity = sysCompService.getCompanyById(compId);
        if(sysUserEntity.getEmail() !=null){
            String email =sysParamsService.getValue(EAMIL);
            // TODO 多语言
            if(email.equals(YES)){
                sysEmailService.sendEmailByManager(sysUserEntity.getEmail(),sysCompEntity.getName(),"拒绝");
            }
        }
        if (sysUserEntity.getMobile() !=null){
            String sms =sysParamsService.getValue(SMS);
            if(sms.equals(YES)){
                SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                        SMS.value(), MsgTypeEnum.MANAGER_AGREE_REFUSE.value());
                String smsCode =sysCompEntity.getName() +"|"+ "拒绝";
                //短信服务
                AbstractSmsService service = SmsFactory.build();
                if(service == null){
                    throw new RenException(ErrorCode.SMS_CONFIG);
                }
                service.sendSmsByLogin(sysUserEntity.getMobile(),sysMsgSendWayEntity.getMsgTemplateCode(),smsCode);
            }
        }
        SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                STTATION_LETTER.value(), MsgTypeEnum.MANAGER_AGREE_REFUSE.value());
        Object[] titleArray = new Object[]{sysCompEntity.getName()};
        String title = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateTitle(), titleArray);
        Object[] contentArray = new Object[]{sysCompEntity.getName(),"拒绝"};
        String content = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateContent(), contentArray);
        // 发送消息
        Date nowDate = new Date();
        SysMessageEntity sysMessageEntity = new SysMessageEntity();
        sysMessageEntity.setMsgSendWayType(MessageSendWayEnum.APP.value());
        sysMessageEntity.setMsgCompId(sysCompEntity.getId());
        sysMessageEntity.setType(MsgTypeEnum.MANAGER_AGREE_REFUSE.value());
        sysMessageEntity.setCreateDate(nowDate);
        sysMessageEntity.setCreator(SecurityUser.getUser().getId());
        sysMessageEntity.setReceiverId(userId);
        // 0是未读，1是已读
        sysMessageEntity.setIsRead(0);
        sysMessageEntity.setSendDate(nowDate);
        sysMessageEntity.setSenderId(sysCompEntity.getAdminUserId());
        sysMessageEntity.setContent(content);
        sysMessageEntity.setTitle(title);
        sysMessageEntity.setUpdateDate(nowDate);
        sysMessageEntity.setUpdater(SecurityUser.getUser().getId());
        sysMessageEntity.setUpdateTimestamp(Long.toString(System.currentTimeMillis()));
        sysMessageService.insert(sysMessageEntity);
    }

    @Override
    public PageInfo<CompSysUserApplEntity> getUserApplList(CompSysUserApplPageDTO compSysUserApplPageDTO) {
        Integer pageSize = compSysUserApplPageDTO.getPageSize();
        Integer page = compSysUserApplPageDTO.getPage();
        if (pageSize > 0 && page > 0) {
            PageHelper.startPage(page, pageSize);
        }
        List<CompSysUserApplEntity> compSysUserApplEntities
                = baseDao.getUserApplList(compSysUserApplPageDTO.getCompId(), compSysUserApplPageDTO.getPram(), DateUtils.dealDateFormat(compSysUserApplPageDTO.getBeginDate()), DateUtils.dealDateFormat(compSysUserApplPageDTO.getEndDate()));
        for (CompSysUserApplEntity compSysUserEmplEntityPageInfo : compSysUserApplEntities) {
            if (compSysUserEmplEntityPageInfo.getHeadUrl() !=null) {
                compSysUserEmplEntityPageInfo.setHeadUrl(Objects.requireNonNull(OSSFactory.build()).getHeadUrl(compSysUserEmplEntityPageInfo.getHeadUrl()));
            }
        }
        return new PageInfo<>(compSysUserApplEntities);
    }

    @Override
    public CompSysUserApplEntity findByUserIdAndCompId(Long compId, Long userId) {
        return baseDao.findByCompIdAndUserId(compId, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateComUserAppl(CompSysUserApplEntity compSysUserApplEntity) {
        baseDao.updateComUserAppl(compSysUserApplEntity);
    }

    @Override
    public int getApplCount(Long compId) {
        return baseDao.getApplCount(compId);
    }
}
